package com.mcxx.modules.minimumliving.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.MQConstant;
import com.mcxx.convert.OrderConvert;
import com.mcxx.modules.minimumliving.service.BacklogService;
import com.mcxx.modules.minimumliving.service.SalvationApplyService;
import com.mcxx.modules.minimumliving.service.ScheduleCheckService;
import com.mcxx.modules.minimumliving.service.SuspendManagementService;
import com.mcxx.modules.base.service.read.ActivitiReadService;
import com.mcxx.modules.base.service.read.RuleEngineReadService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.check.entity.CheckEntity;
import com.mcxx.modules.miniSalvation.check.service.read.CheckReadService;
import com.mcxx.modules.miniSalvation.check.service.write.CheckWriteService;
import com.mcxx.modules.miniSalvation.family.dto.DemocraticAppraisalDTO;
import com.mcxx.modules.miniSalvation.family.dto.MemberAssetsDTO;
import com.mcxx.modules.miniSalvation.family.dto.MemberSalaryOrderDTO;
import com.mcxx.modules.miniSalvation.family.dto.SalvationFamilyDTO;
import com.mcxx.modules.miniSalvation.family.entity.BankEntity;
import com.mcxx.modules.miniSalvation.family.entity.DemocraticAppraisalEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.service.read.*;
import com.mcxx.modules.miniSalvation.family.service.write.*;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.dto.*;
import com.mcxx.modules.miniSalvation.order.entity.OrderDetailEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderStateEntity;
import com.mcxx.modules.miniSalvation.order.param.ActivitiParam;
import com.mcxx.modules.miniSalvation.order.param.OrderListSearchParam;
import com.mcxx.modules.miniSalvation.order.service.read.NoticeBoardDetailReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderDetailReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.*;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilySalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.write.FamilySalaryWriteService;
import com.mcxx.modules.miniSalvation.salary.service.write.SalaryChangeWriteService;
import com.mcxx.modules.system.dto.MQMessageDTO;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.*;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;



@Slf4j
@Service
@TaTransactional
public class BacklogServiceImpl implements BacklogService {
    @Autowired
    private CheckWriteService checkWriteService;
    @Autowired
    private CheckReadService checkReadService;
    @Autowired
    private InHouseWriteService inHouseWriteService;
    @Autowired
    private DemocraticAppraisalWriteService democraticAppraisalWriteService;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;
    @Autowired
    private FamilyMainWriteService familyMainWriteService;
    @Autowired
    private FamilyMainReadService familyMainReadService;
    @Autowired
    private OrderDetailWriteService orderDetailWriteService;
    @Autowired
    private FamilySalaryWriteService familySalaryWriteService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private ActivitiReadService activitiReadService;
    @Autowired
    private FamilyMainHistoryWriteService familyMainHistoryWriteService;
    @Autowired
    private SalaryChangeWriteService salaryChangeWriteService;
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private OrderDetailReadService orderDetailReadService;
    @Autowired
    private AppraisalReadService appraisalReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private RuleEngineReadService ruleEngineReadService;
    @Autowired
    private MemberAssetsReadService memberAssetsReadService;
    @Autowired
    private NoticeBoardDetailReadService noticeBoardDetailReadService;
    @Autowired
    private SalvationApplyService salvationApplyService;
    @Autowired
    private OrderCertReadService orderCertReadService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ScheduleCheckService scheduleCheckService;
    @Autowired
    private BankReadService bankReadService;
    @Resource
    private ExportExcelService exportExcelService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private FamilySalaryReadService familySalaryReadService;
    @Autowired
    private RecheckBatchWriteService recheckBatchWriteService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private SuspendManagementService suspendManagementService;
    @Autowired
    private NoticeBoardDetailWriteService noticeBoardDetailWriteService;




    @Override
    public Map<String, List<String>> sendCheck(List<CheckDTO> checkList, UserAccountVo userAccountVo, String businessType,String checkType) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();


        checkList = this.verifyInfComp(checkList, idcardCheckRstMsg);
        if(checkList.size() == 0){

            return idcardCheckRstMsg;
        }


        this.verifyNoCompleteCheck(checkList, idcardCheckRstMsg);
        if(checkList.size() == 0){

            return idcardCheckRstMsg;
        }


        log.info("开始保存数据到check表");
        checkWriteService.addCheck(checkList, userAccountVo.getAreaCode(), Constant.CheckState.WIAT_SEND, checkType, businessType);





        List<String> successIdcardList = checkList.stream().map(CheckDTO::getIdcard).collect(Collectors.toList());


        idcardCheckRstMsg.put("success", successIdcardList);


        log.info("发送数据给核对中心");
        String checkMsg = scheduleCheckService.sendCheckInfo(checkList,Constant.BusinessCode.DIBAO,userAccountVo,checkType);
        if(StringUtils.isNotBlank(checkMsg)){
            idcardCheckRstMsg.put("checkMsg",Arrays.asList(checkMsg));
        }

        return idcardCheckRstMsg;
    }


    public List<String> verifyFamilyMasterNum(List<CheckDTO> checkList){
        List<String> masterNumErrorIdcard = new ArrayList<>();

        Map<String, CheckDTO> noIdCardCheckDTOMap = checkList.stream().filter(c -> CommonUtil.invalidArgs(c.getIdcard())).collect(Collectors.toMap(CheckDTO::getFamilyId, c -> c));

        List<String> noIdCardFamilyIdList = new ArrayList<>(noIdCardCheckDTOMap.keySet());
        if(CollectionUtils.isNotEmpty(noIdCardFamilyIdList)){

            List<FamilyMemberEntity> familyMasterIdcardList =  familyMemberReadService.getMasterByFamilyIds(noIdCardFamilyIdList);

            familyMasterIdcardList.forEach(familyMemberEntity -> {
                noIdCardCheckDTOMap.get(familyMemberEntity.getFamilyId()).setIdcard(familyMemberEntity.getIdcard());
                noIdCardCheckDTOMap.remove(familyMemberEntity.getFamilyId());
            });
        }


        if(noIdCardCheckDTOMap.size() > 0){
            masterNumErrorIdcard = noIdCardCheckDTOMap.values().stream().map(c->c.getApplyIdcard()).collect(Collectors.toList());
        }

        checkList.removeAll(noIdCardCheckDTOMap.values());

        return masterNumErrorIdcard;
    }


    private List<CheckDTO> verifyInfComp(List<CheckDTO> checkList,  Map<String, List<String>> idcardCheckRstMsg){


        List<String>  masterNumErrorIdcardList = this.verifyFamilyMasterNum(checkList);
        if(CollectionUtils.isNotEmpty(masterNumErrorIdcardList)){
            idcardCheckRstMsg.put("masterNumError", masterNumErrorIdcardList);
        }
        if(checkList.size() == 0){

            return checkList;
        }

        Map<String, CheckDTO> idcardCheckDTOMap = checkList.stream().collect(Collectors.toMap(CheckDTO::getIdcard, c -> c));
        Map<String, String> familyIdIdcardMap = checkList.stream().collect(Collectors.toMap(CheckDTO::getFamilyId, CheckDTO::getIdcard));


        List<String>  memberInfoNoCompleteIdcard = salvationApplyService.verifyCompleteMemberInfo(familyIdIdcardMap);
        if(CollectionUtils.isNotEmpty(memberInfoNoCompleteIdcard)){
            idcardCheckRstMsg.put("memberInfoError", memberInfoNoCompleteIdcard);

            for(String idcard : memberInfoNoCompleteIdcard){
                checkList.remove(idcardCheckDTOMap.get(idcard));
            }
        }
        if(checkList.size() == 0){

            return checkList;
        }
        int calculateFlag = orderReadService.selectOrderInCalculate(checkList.get(0).getOrderId());

        Map<String, String> orderIdIdcardMap = checkList.stream().collect(Collectors.toMap(CheckDTO::getOrderId, CheckDTO::getIdcard));

        if(calculateFlag==0){
            List<String> noExistsAssestsIdcard = salvationApplyService.verifyMemberAssetsList(orderIdIdcardMap);
            if(CollectionUtils.isNotEmpty(noExistsAssestsIdcard)){
                idcardCheckRstMsg.put("noExistsAssests", noExistsAssestsIdcard);

                for(String idcard : noExistsAssestsIdcard){
                    checkList.remove(idcardCheckDTOMap.get(idcard));
                }
            }
            if(checkList.size() == 0){

                return checkList;
            }
        }

        orderIdIdcardMap = checkList.stream().collect(Collectors.toMap(CheckDTO::getOrderId, CheckDTO::getIdcard));
        List<String> noExistsCertOrderIdList = orderCertReadService.getSQSNumByOrderIds(new ArrayList<>(orderIdIdcardMap.keySet()));
        if(CollectionUtils.isNotEmpty(noExistsCertOrderIdList)){

            List<String> noExistsCertIdcardList = new ArrayList<>();
            for(String orderId : noExistsCertOrderIdList){
                noExistsCertIdcardList.add(orderIdIdcardMap.get(orderId));
                checkList.remove(idcardCheckDTOMap.get(orderIdIdcardMap.get(orderId)));
            }
            idcardCheckRstMsg.put("noExistCert", noExistsCertIdcardList);
        }
        if(checkList.size() == 0){

            return checkList;
        }


        orderIdIdcardMap = checkList.stream().collect(Collectors.toMap(CheckDTO::getOrderId, CheckDTO::getIdcard));
        List<String> memberNoExistsCertOrderIdList = orderCertReadService.getOrderIdNoIdcardCert(new ArrayList<>(orderIdIdcardMap.keySet()));
        if(CollectionUtils.isNotEmpty(memberNoExistsCertOrderIdList)){
            List<String> noExistsCertIdcardList = new ArrayList<>();
            for(String orderId : memberNoExistsCertOrderIdList){
                noExistsCertIdcardList.add(orderIdIdcardMap.get(orderId));
                checkList.remove(idcardCheckDTOMap.get(orderIdIdcardMap.get(orderId)));
            }

            idcardCheckRstMsg.put("memberNoExistCert", noExistsCertIdcardList);
        }
        if(checkList.size() == 0){

            return checkList;
        }


        List<String> noIdCardSupport = orderCertReadService.cntSupportCertBeforeCheck(checkList);
        if(CollectionUtils.isNotEmpty(noIdCardSupport)){
            idcardCheckRstMsg.put("noIdCardSupport",noIdCardSupport);

            for(String idcard:noIdCardSupport){
                checkList.remove(idcardCheckDTOMap.get(idcard));
            }
        }
        if(checkList.size() == 0){

            return checkList;
        }

        if("1".equals(checkList.get(0).getFamilySupport())){

            List<String> noAuthorSupport = orderCertReadService.selectSupportAuthorList(checkList.stream().map(o->o.getOrderId()).collect(Collectors.toList()));
            if(CollectionUtils.isNotEmpty(noAuthorSupport)){
                idcardCheckRstMsg.put("noAuthorSupport",noAuthorSupport);

                for(String idcard:noAuthorSupport){
                    checkList.remove(idcardCheckDTOMap.get(idcard));
                }
            }
            if(checkList.size() == 0){

                return checkList;
            }
        }

        List <String> noBackUpOrder = orderReadService.cntFileObjId(checkList.stream().map(c->c.getOrderId()).collect(Collectors.toList()));
        if(CollectionUtils.isNotEmpty(noBackUpOrder)){
            idcardCheckRstMsg.put("noBackUpOrder",noBackUpOrder);
            for(String idcard:noBackUpOrder){
                checkList.remove(idcardCheckDTOMap.get(idcard));
            }
        }
        return checkList;
    }


    public void verifyNoCompleteCheck(List<CheckDTO> checkList, Map<String, List<String>> idcardCheckRstMsg){
        List<String> canNotSendCheckIdcardLsit = new ArrayList<>();


        List<String> familyIdList = checkList.stream().map(CheckDTO::getFamilyId).collect(Collectors.toList());


        List<String> noReportFamilyIdList = checkReadService.getNoCompleteFamilyId(familyIdList);


        if(noReportFamilyIdList.size() > 0){

            Map<String, CheckDTO> checkDTOMap = checkList.stream().collect(Collectors.toMap(c->c.getFamilyId(), c -> c));


            noReportFamilyIdList.forEach(familyId -> {
                checkList.remove(checkDTOMap.get(familyId));
                canNotSendCheckIdcardLsit.add(checkDTOMap.get(familyId).getIdcard());
            });


            idcardCheckRstMsg.put("canNotSendCheck", canNotSendCheckIdcardLsit);
        }
    }





    @Override
    public byte[] getCheckReportFile(String fileKey,String fileType){
        if("1".equals(fileType)){
            byte[] bytes = fileService.download(fileKey);
            return bytes;
        }


        String flag = checkReadService.selectCheckFileType(fileKey);

        byte[] bytes = null;
        if(!"3".equals(flag)){
            bytes = fileService.downloadCheckFile(fileKey);
        }else{
            bytes = fileService.download(fileKey);
        }

        return bytes;
    }


    @Override
    public void isCanInHouse(String orderId, UserAccountVo userAccountVo) {

        List<String> idCardList = orderReadService.cntFileObjId(Arrays.asList(orderId));
        if(idCardList!=null&&idCardList.size()>0){
            throw new BizException(FailureCode.ERR_20084);
        }

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);


        String bizStateType = Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())
                ? Constant.OrderBizStateType.START_TOWN_IN_HOUSE
                : Constant.OrderBizStateType.START_TOWN_IN_HOUS_COUNTY;


        ruleEngineReadService.getBizStateRuleThrow(bizStateType, orderStateVerifyDTO, userAccountVo);
    }


    @Override
    public void isCanInHouseRecheck(String orderId, UserAccountVo userAccountVo) {

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);


        String bizStateType = Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())
                ? Constant.OrderBizStateType.START_TOWN_IN_HOUSE
                : Constant.OrderBizStateType.START_TOWN_IN_HOUS_COUNTY;

        if(Constant.OrderBizStateType.START_TOWN_IN_HOUSE.equals(bizStateType)){
            orderStateVerifyDTO.setNextCondition(orderStateVerifyDTO.getBizState());
        }

        ruleEngineReadService.getRecheckBizStateRuleThrow(bizStateType, orderStateVerifyDTO, userAccountVo);
    }




    @Override
    public String saveInHouseRecord(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo) {

        this.isCanInHouse(orderInHouse.getOrderId(), userAccountVo);


        OrderDTO orderDTO = orderReadService.getStateAndVersion(orderInHouse.getOrderId());


        if(CommonUtil.invalidArgs(orderInHouse.getId())){
            inHouseWriteService.addInHouse(orderInHouse, orderCertIdList, userAccountVo);

            String bizState = Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel()) ? Constant.BizState.YES_IN_HOUSE : Constant.BizState.COUNTY_YES_IN_HOUSE;
            orderWriteService.updateOrderState(orderDTO, orderDTO.getBizState(), bizState);
        }else{
            inHouseWriteService.updateById(orderInHouse, orderCertIdList, userAccountVo);
        }

        return orderInHouse.getId();
    }


    @Override
    public void modifyInHouseRecord(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo) {

        this.isCanInHouse(orderInHouse.getOrderId(), userAccountVo);


        inHouseWriteService.updateById(orderInHouse, orderCertIdList, userAccountVo);
    }



    @Override
    public String confirmInhouseRecordCounty(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo) {

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderInHouse.getOrderId());

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE_COUNTY, orderStateVerifyDTO, userAccountVo);


        OrderDTO orderDTO = orderReadService.getStateAndVersion(orderInHouse.getOrderId());

        if(CommonUtil.invalidArgs(orderInHouse.getId())){

            inHouseWriteService.addInHouse(orderInHouse,orderCertIdList,userAccountVo);
        }else{

            inHouseWriteService.updateById(orderInHouse, orderCertIdList, userAccountVo);
        }

        orderWriteService.updateOrderState(orderDTO, orderDTO.getBizState(), orderStateVerifyDTO.getNextBizState());
        return orderInHouse.getId();
    }


    @Override
    public void isCanDemocraticAppraisal(String orderId, UserAccountVo userAccountVo) {

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_APPRAISAL, orderStateVerifyDTO, userAccountVo);
    }

    @Override
    public void reCheckCanDemocraticAppraisal(String orderId, UserAccountVo userAccountVo) {

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);
        if(Constant.BizStateNew.CONFIRM_APPROVE.equals(orderStateVerifyDTO.getBizState())){
            int count= appraisalReadService.selectCountByOrderId(orderId);
            if(count > 0){
                throw new BizException("-1","已经民主评议过，无法再次进行该流程");
            }
        }

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_APPRAISAL, orderStateVerifyDTO, userAccountVo);
    }


    @Override
    public String addDemocraticAppraisal(DemocraticAppraisalEntity democraticAppraisalEntity, List<String> orderCertIdList, UserAccountVo userAccountVo){

        this.isCanDemocraticAppraisal(democraticAppraisalEntity.getOrderId(), userAccountVo);


        OrderDTO orderDTO = orderReadService.getStateAndVersion(democraticAppraisalEntity.getOrderId());

        String bizState = Constant.BizStateNew.APPRAISAL_ING;
        if("2".equals(democraticAppraisalEntity.getType())){
            bizState = Constant.BizStateNew.CONFIRM_APPROVE;
            democraticAppraisalEntity.setAppraisalResult("1");

            int i = orderCertReadService.queryCertIsExiten(new ArrayList<String>() {{
                add(democraticAppraisalEntity.getOrderId());
            }}, "601", "5");
            int j = orderCertReadService.queryCertIsExiten(new ArrayList<String>() {{
                add(democraticAppraisalEntity.getOrderId());
            }}, "602", "5");
            if (i <= 0 || j <= 0) {
                throw new BizException("-1", "请上传民主评议证明材料");
            }
        }

        int rst = democraticAppraisalWriteService.addDemocraticAppraisal(democraticAppraisalEntity, orderCertIdList);;
        if(rst <= 0){
            log.info("orderId = {},说明新增民主评议信息失败", democraticAppraisalEntity.getOrderId());
            throw new BizException("-1", "新增民主评议信息失败");
        }

        orderWriteService.updateOrderState(orderDTO, orderDTO.getBizState(), bizState);

        return democraticAppraisalEntity.getId();
    }


    @Override
    public void cancelSalvationRequestTown(String orderId,  String revokeReason,UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.TOWN_REVOKE, orderStateVerifyDTO, userAccountVo);


        orderWriteService.backUpOrder(orderStateVerifyDTO);


        OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
        orderDetailEntity.setOrderId(orderId);
        orderDetailEntity.setCheckType(Constant.CheckDatailStatus.revoke);
        orderDetailEntity.setBusinessStatus(Constant.RemarkOperType.STREET);
        orderDetailEntity.setCheckResult(Constant.AudtiOrApprovalResult.REVOKE);
        orderDetailEntity.setCheckOpinion(revokeReason);
        orderDetailEntity.setCheckPeople(userAccountVo.getUsername());
        orderDetailEntity.setCheckDate(new Date());
        orderDetailEntity.setOperator(userAccountVo.getLoginId());
        orderDetailEntity.setOrgId(userAccountVo.getOrgId());
        orderDetailEntity.setCreateBy(userAccountVo.getUserId());
        orderDetailWriteService.insertSalvationAudit(orderDetailEntity);


        familySalaryWriteService.deleteSalaryByOrderId(orderId);


        noticeBoardDetailWriteService.deleteByOrderId(orderId);
    }


    @Override
    public Map<String, List<String>> cancelSalvationRequestTowns(List<String> orderIdList, UserAccountVo userAccountVo){
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();

        List<OrderStateVerifyDTO> orderStateVerifyList = orderReadService.getBizStateReportFileList(orderIdList);
        List<String> notStateIdcardList = new ArrayList<>();


        orderStateVerifyList.forEach(orderStateVerifyDTO -> {

            orderStateVerifyDTO.setNextCondition("4");
            boolean mark = ruleEngineReadService.getBizStateRule(Constant.OrderBizStateType.TOWN_DELETE, orderStateVerifyDTO, userAccountVo);
            if(mark){

                orderWriteService.revokeOrder(orderStateVerifyDTO);

                this.deleteBankInfo(orderStateVerifyDTO.getFamilyId(), orderStateVerifyDTO.getBusinessType());

                scheduleCheckService.repealUnfinishCheck(orderStateVerifyDTO.getOrderId(),userAccountVo);
            }else{
                notStateIdcardList.add(orderStateVerifyDTO.getIdcard());
            }
        });
        if (CollectionUtils.isNotEmpty(notStateIdcardList)) {
            idcardCheckRstMsg.put("noExistState", notStateIdcardList);
        }

        return idcardCheckRstMsg;
    }

    public void deleteBankInfo(String familyId, String businessType){

        List<BankEntity> bankEntityList = bankReadService.getBankByfamilyId(familyId,businessType);
        if(!CollectionUtils.isEmpty(bankEntityList)) {
            bankWriteService.deleteBankInfo(bankEntityList.get(0).getId());
        }
    }


    @Override
    public BaseResult<OrderDetailDTO> getOrderDetail(String orderId, String checkDetailStatus){
        BaseResult<OrderDetailDTO> rstMsg = new BaseResult<>();
        rstMsg.setCode("1");
        rstMsg.setMsg("操作成功");


        OrderDetailDTO orderDetail = orderDetailReadService.getOrderDetail(orderId, checkDetailStatus);
        if(null != orderDetail){
            orderDetail.setCheckDate(null);
        }
        rstMsg.setData(orderDetail);
        return rstMsg;
    }


    @Override
    public Map<String,Object> getInfoBeforeAudit(String orderId){
        BaseResult<Map> rstMsg = new BaseResult<>();
        rstMsg.setCode("1");
        rstMsg.setMsg("操作成功");
        Map<String,Object> map = new HashMap<>();

        List<MemberSalaryOrderDTO> memberInfoByFamilyId = familyMemberReadService.getMemberInfoByOrderId(orderId);

        NoticeBoardDetailDTO noticeDetail = noticeBoardDetailReadService.selectHasObjection(orderId);

        List<NoticeBoardDetailDTO> noticeList = new ArrayList<>();
        if(!CommonUtil.invalidArgs(noticeDetail)){

            DemocraticAppraisalDTO appraisalDTO = appraisalReadService.selectAppraisalInfo(orderId);
            if(!CommonUtil.invalidArgs(appraisalDTO)){
                noticeDetail.setAppaisalContent(appraisalDTO.getAppraisalContent());
                noticeDetail.setAppraisalDate(appraisalDTO.getAppraisalDate());
                noticeDetail.setHost(appraisalDTO.getHost());
                noticeDetail.setRecorder(appraisalDTO.getRecorder());
            }
            noticeList.add(noticeDetail);
        }

        List<OrderApproveDTO> approveList = orderDetailReadService.getApproveList(orderId, Constant.CheckDatailStatus.Pi,"2");

        String bizState = orderReadService.getBizStateById(orderId);
        if(Constant.BizStateNew.COUNTY_APPROVE_ING.equals(bizState)){

            OrderApproveDTO salvationApprove = orderDetailReadService.getSaveSalvation(orderId, Constant.CheckDatailStatus.Pi);
            approveList = approveList.stream().filter(orderApproveDTO -> !orderApproveDTO.getOrderDetailId().equals(salvationApprove.getOrderDetailId())).collect(Collectors.toList());
            map.put("orderDetail",salvationApprove);
        }

        String salvationNo = orderDetailReadService.getSalvationNo(orderId);

        map.put("salvationNo",salvationNo);
        map.put("familyMemberInfo",memberInfoByFamilyId);
        map.put("noticeInfo",noticeList);
        map.put("approveList",approveList);


        map.put("currDate", new Date());
        return map;
    }

    @Override
    public BaseResult<OrderApproveDTO> getSalvationApprove(String orderId){
        BaseResult<OrderApproveDTO> rstMsg = new BaseResult<>();
        rstMsg.setCode("1");
        rstMsg.setMsg("操作成功");


        rstMsg.setData(orderDetailReadService.getSalvationApprove(orderId, Constant.CheckDatailStatus.Pi));

        return rstMsg;
    }


    @Override
    public void saveSalvationAudit(OrderReviewDTO orderReviewDTO, UserAccountVo userAccountVo) {

        OrderEntity updateOrderEntity = new OrderEntity();


        OrderStateVerifyDTO orderStateVerifyDTO = this.isCanAudit(orderReviewDTO.getOrderId(), orderReviewDTO.getSubmitType(), orderReviewDTO.getCheckResult(), userAccountVo);


//        salvationApplyService.verifyMemberAssets(orderStateVerifyDTO.getOrderId());


        orderDetailWriteService.saveAuditDetail(orderReviewDTO, userAccountVo);



        SalvationFamilyDTO salvationFamilyDTO = orderReadService.getOrderFamilyInfo(orderReviewDTO.getOrderId());
        if(salvationFamilyDTO != null && Constant.MinimumLivingType.HOUSEHOLD.equals(salvationFamilyDTO.getFamilyObjectType())){

            if(!"0".equals(salvationFamilyDTO.getSaveMemberNumber()) && !salvationFamilyDTO.getSaveMemberNumber().equals(salvationFamilyDTO.getFamilyNumber())){
                throw new BizException("-1","整户保家庭不能存在非在保对象");
            }
        }


        this.auditUpdateOrderState(updateOrderEntity, orderStateVerifyDTO,null);


        //this.auditRefuse(orderStateVerifyDTO.getNextState(), orderReviewDTO, orderStateVerifyDTO.getFamilyId(), userAccountVo);
    }


    public void auditUpdateOrderState(OrderEntity updateOrderEntity, OrderStateVerifyDTO orderStateVerifyDTO,String rescueYears){
        updateOrderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
        updateOrderEntity.setVersion(orderStateVerifyDTO.getVersion());
        updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
        updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
        if(StringUtils.isNotEmpty(rescueYears)){
            updateOrderEntity.setStartMonth(rescueYears);
        }
        orderWriteService.updateIgnoreNull(updateOrderEntity);
    }


    @Override
    public int isCanCalcFamilySalary(String orderId) {

        String bizState = orderReadService.getBizStateByBizStateRange(orderId, Constant.BizState.YES_IN_HOUSE);
        if(CommonUtil.invalidArgs(bizState)){

            throw new BizException("-1", "未进行入户调查，无法计算待遇");
        }

        if(Constant.BizStateNew.APPROVE_REJECT.equals(bizState) == false){

            return 1;
        }


        String checkReportFile = checkReadService.getCheckFileObjectKey(orderId);
        if(CommonUtil.invalidArgs(checkReportFile)){

            throw new BizException("-1", "已发起核对，但还没有收到核对报告，无法计算待遇");
        }

        return 1;
    }



    public void auditRefuse(String nextState, OrderReviewDTO orderReviewDTO, String familyId, UserAccountVo userAccountVo){
        if(Constant.BizStateNew.AUDIT_REFUSE.equals(nextState) == false){
            return;
        }

        familyMainHistoryWriteService.backHistory(orderReviewDTO.getOrderId(), familyId, null, null, userAccountVo);


        familySalaryWriteService.deleteSalaryByOrderId(orderReviewDTO.getOrderId());
    }


    @Override
    public OrderStateVerifyDTO isCanAudit(String orderId, String submitType, String nextCondition, UserAccountVo userAccountVo) {
        int houseHoldCancel =  familyMemberReadService.isHouseholdCancel(orderId);

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);

//        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getState())){

        if(houseHoldCancel<1){
            salvationApplyService.verifyCompleteMemberInfo(orderStateVerifyDTO.getFamilyId());
            salvationApplyService.verifyCert(orderId,orderStateVerifyDTO.getFamilyId(),null);
            salvationApplyService.verifyFamilyMasterNum(orderStateVerifyDTO.getFamilyId());
        }


        if("1".equals(submitType)){
            orderStateVerifyDTO.setNextCondition("2");
        }else{

            int count =  orderReadService.selectOrderInCalculate(orderId);
            if(count<1){

                if(houseHoldCancel<1){

                    List<MemberAssetsDTO> list = memberAssetsReadService.queryListByFamilyId(orderStateVerifyDTO.getFamilyId(), orderStateVerifyDTO.getOrderId(),"");
                    if(CollectionUtils.isEmpty(list)){
                        throw new BizException(FailureCode.ERR_20068);
                    }
                }
            }

            orderStateVerifyDTO.setNextCondition(Constant.BizStateNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getState()) ? "4" : "3");
        }


        String bizStateType = "1".equals(submitType) ? Constant.OrderBizStateType.START_TOWN_AUDIT : Constant.OrderBizStateType.COMPLETE_TOWN_AUDIT;


        ruleEngineReadService.getBizStateRuleThrow(bizStateType, orderStateVerifyDTO, userAccountVo);


        return orderStateVerifyDTO;
    }


    @Override
    public void isCanAuditRecheck(String orderId,String familyId,UserAccountVo userAccountVo) {


        salvationApplyService.verifyFamilyMasterNum(familyId);




        salvationApplyService.verifyCompleteMemberInfo(familyId);


        salvationApplyService.verifyOrderNoReason(orderId);

        int count = familyMemberReadService.isHouseholdCancel(orderId);
        if(count==0){

            salvationApplyService.verifyCert(orderId, familyId,null);

            salvationApplyService.verifyfamilyRevenue(familyId);
        }

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);
        orderStateVerifyDTO.setNextCondition("2");
        ruleEngineReadService.getRecheckBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_AUDIT, orderStateVerifyDTO, userAccountVo);
    }


    private void checkNoticeBoardForSubmit(OrderDTO orderDTO){
        if(Constant.OrderType.RECHECK.equals(orderDTO.getType())){

            return;
        }
        int rst = orderReadService.cntByOrderAndBizState(orderDTO.getId(), Constant.BizState.NOTICE_BOARD_COMPLETE);
        if(rst <= 0){
            log.info("{}公示未结束，不可以保存审核信息", orderDTO.getId());
            throw new BizException("-1", "公示未结束，不可以保存审核信息");
        }
    }

    @Override
    public  int submitSalvationRequest(OrderReviewDTO orderReviewDTO, UserAccountVo userAccountVo){


        OrderDTO orderDTO = orderReadService.getStateAndVersion(orderReviewDTO.getOrderId());


        this.checkNoticeBoardForSubmit(orderDTO);


        ActivitiParam activitiParam = new ActivitiParam(orderDTO.getState(), orderReviewDTO.getCheckResult(), orderDTO.getSalvMoney(),Constant.BusinessCode.DIBAO);
        String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());
        if("-1".equals(nextActviti)){
            log.info("{}账号没有保存审核信息的信息", userAccountVo.getName());
            throw new BizException("-1", "账号没有保存审核信息的信息");
        }


        log.info("将审核DTO对象转换为entity");
        OrderDetailEntity orderDetailEntity = OrderConvert.convertOrderDetailEntity(orderReviewDTO, userAccountVo);
        orderDetailEntity.setBusinessStatus(Constant.RemarkOperType.STREET);
        orderDetailEntity.setCheckType(Constant.CheckDatailStatus.he);


        log.info("执行审核信息保存的update语句");
        int rst = 0;
        if(CommonUtil.invalidArgs(orderReviewDTO.getOrderDetailId()) == true){

            orderDetailEntity.setId(Constant.getUUID());
            rst = orderDetailWriteService.insertSalvationAudit(orderDetailEntity);
        }else{

            orderDetailEntity.setId(orderReviewDTO.getOrderDetailId());
            rst = orderDetailWriteService.updateSalvationAudit(orderDetailEntity);
        }
        if(rst <= 0){
            throw new BizException("-1", "审核信息更新失败");
        }


        this.rejectOrderCalcSalary(orderDTO, userAccountVo);


        orderWriteService.updateOrderNextActviti(orderDTO, nextActviti,  Constant.BizState.APPROVE_ING);


        return  1;

    }


    @Override
    public Map<String, List<String>> exceBatchReport(List<String> orderIdList, UserAccountVo userAccountVo) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();

        List<OrderStateVerifyDTO> needSendCheckOrderList = orderReadService.getBizStateReportFileList(orderIdList);
        List<String> notStateIdcardList = new ArrayList<>();


        needSendCheckOrderList.forEach(orderStateVerifyDTO -> {
            orderStateVerifyDTO.setNextCondition(orderStateVerifyDTO.getState());
            boolean mark = ruleEngineReadService.getBizStateRule(Constant.OrderBizStateType.TOWN_SUBMIT, orderStateVerifyDTO, userAccountVo);
            if(mark){
                OrderEntity updateOrderEntity = new OrderEntity();
                updateOrderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
                updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
                updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
                updateOrderEntity.setVersion(orderStateVerifyDTO.getVersion());

                orderWriteService.updateIgnoreNull(updateOrderEntity);
            }else{
                notStateIdcardList.add(orderStateVerifyDTO.getIdcard());
            }
        });
        if (CollectionUtils.isNotEmpty(notStateIdcardList)) {
            idcardCheckRstMsg.put("noExistState", notStateIdcardList);
        }
        return idcardCheckRstMsg;
    }


    public void rejectOrderCalcSalary(OrderDTO orderDTO, UserAccountVo userAccountVo){

        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderDTO.getBizState())){
            OrderSalaryDTO orderSalaryParam = orderReadService.getSalaryInfo(orderDTO.getId());
            familySalaryWriteService.saveFamilySalaryDiBao(orderSalaryParam, userAccountVo);
        }
    }






    @Override
    public void isCanInHouseCounty(String orderId,UserAccountVo userAccountVo) {

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_IN_HOUS_COUNTY, orderStateVerifyDTO, userAccountVo);
    }


    @Override
    public void isCanAuditCounty(String orderId, UserAccountVo userAccountVo) {


        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.START_COUNTY_APPROVE, orderStateVerifyDTO, userAccountVo);
    }


    @Override
    public String saveInHouseRecordCounty(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo) {

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderInHouse.getOrderId());

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.ORDER_EDIT, orderStateVerifyDTO, userAccountVo);


        int rst = checkReadService.queryByFamilyId(orderInHouse.getFamilyId());
        if(rst <= 0){
            log.info("orderId = {},请先发起核对，再进行入户调查", orderInHouse.getOrderId());
            throw new BizException("-1", "请先发起核对，再进行入户调查");
        }


        OrderDTO orderDTO = orderReadService.getStateAndVersion(orderInHouse.getOrderId());


        rst = inHouseWriteService.addInHouse(orderInHouse, orderCertIdList, userAccountVo);
        if(rst <= 0){
            log.info("orderId = {},说明新增入户调查信息失败", orderInHouse.getOrderId());
            throw new BizException("-1", "入户调查信息条件失败");
        }


        OrderStateEntity orderStateEntity = new OrderStateEntity(orderDTO.getId(),
                orderStateVerifyDTO.getNextBizState(),orderStateVerifyDTO.getNextBizState(),
                null,
                orderDTO.getVersion());
        rst = orderWriteService.updateState(orderStateEntity);
        if(rst <= 0){
            log.info("orderId = {},说明修改状态信息失败", orderDTO.getId());
            throw new BizException("-1", "订单状态异常，修改失败");
        }

        return orderInHouse.getId();
    }


    @Override
    public int modifyInHouseRecordCounty(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo) {

        OrderDTO orderDTO = orderReadService.getStateAndVersion(orderInHouse.getOrderId());


        inHouseWriteService.updateById(orderInHouse, orderCertIdList, userAccountVo);


        OrderStateEntity orderStateEntity = new OrderStateEntity(orderDTO.getId(),
                Constant.BizState.COUNTY_YES_IN_HOUSE, Constant.BizState.COUNTY_YES_IN_HOUSE,
                null,
                orderDTO.getVersion());
        int rst = orderWriteService.updateState(orderStateEntity);
        if(rst <= 0){
            log.info("orderId = {},说明修改状态信息失败", orderDTO.getId());
            throw new BizException("-1", "订单状态异常，修改失败");
        }

        return 1;
    }


    public OrderStateVerifyDTO isCanApprove(String orderId, UserAccountVo userAccountVo, String submitType,String approvalResult){

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);


        String bizStateType = "1".equals(submitType) ? Constant.OrderBizStateType.START_COUNTY_APPROVE : Constant.OrderBizStateType.COMPLETE_COUNTY_APPROVE;
        if("2".equals(submitType)){

            orderStateVerifyDTO.setNextCondition(approvalResult);
        }


        ruleEngineReadService.getBizStateRuleThrow(bizStateType, orderStateVerifyDTO, userAccountVo);


        return orderStateVerifyDTO;
    }


    public void approveUpdateOrderState(OrderStateVerifyDTO orderStateVerifyDTO, OrderApproveDTO orderApproveDTO){
        OrderEntity updateOrderEntity = new OrderEntity();
        updateOrderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
        updateOrderEntity.setVersion(orderStateVerifyDTO.getVersion());
        updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
        updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
        updateOrderEntity.setCheckDate(new Date());
        updateOrderEntity.setStartMonth(orderApproveDTO.getRescueYears());
        updateOrderEntity.setEndMonth(Constant.MAX_YEAR);
        updateOrderEntity.setSaveMemberNumber(orderStateVerifyDTO.getReportNum());
        orderWriteService.updateIgnoreNull(updateOrderEntity);
    }


    public void updateHouseholdCancelOrder(OrderStateVerifyDTO orderStateVerifyDTO, OrderApproveDTO orderApproveDTO){
        OrderEntity updateOrderEntity = new OrderEntity();
        updateOrderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
        updateOrderEntity.setVersion(orderStateVerifyDTO.getVersion());
        updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
        updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
        updateOrderEntity.setSalvMoney((double) 0);
        updateOrderEntity.setCheckDate(new Date());
        updateOrderEntity.setStartMonth(null);
        updateOrderEntity.setEndMonth(null);
        orderWriteService.updateHouseholdOrder(updateOrderEntity);
    }



    @Override
    public String approveSalvationRequest(OrderApproveDTO orderApproveDTO, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = this.isCanApprove(orderApproveDTO.getOrderId(), userAccountVo, "2",orderApproveDTO.getApprovalResult());
        if(Constant.OrderType.NEW.equals(orderStateVerifyDTO.getType())){

            familySalaryReadService.checkFamilyIsSaved(orderApproveDTO.getOrderId(),orderStateVerifyDTO.getFamilyId(),orderApproveDTO.getRescueYears());
        }



        salvationApplyService.verifyMemberAssets(orderApproveDTO.getOrderId());

        if("1".equals(orderApproveDTO.getApprovalResult()) && Constant.OrderType.RECHECK.equals(orderStateVerifyDTO.getType())){
            fundPayReadService.verifySuspendFundPayThrow(orderStateVerifyDTO.getSourOrderId(),orderStateVerifyDTO.getBusinessType(), orderStateVerifyDTO.getCountyCode(),
                    orderStateVerifyDTO.getStandType(), orderApproveDTO.getRescueYears(), orderStateVerifyDTO.getSupplyType());
        }


        log.info("执行审核信息保存的update语句");
        orderDetailWriteService.saveSalvationApprove(orderApproveDTO, userAccountVo);

        familyMainWriteService.updateSalvationNo(orderApproveDTO.getOrderId(),orderApproveDTO.getSalvationNo());


        FamilyMainEntity familyMainEntity = familyMainReadService.getById(orderStateVerifyDTO.getFamilyId());
        orderStateVerifyDTO.setReportNum(familyMainEntity.getSaveMemberNumber());
        this.approveUpdateOrderState(orderStateVerifyDTO, orderApproveDTO);

        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getNextState())){

            return "";
        }


        familyMemberWriteService.updateFirstStartDate(orderStateVerifyDTO.getType(),orderApproveDTO.getOrderId(),orderStateVerifyDTO.getBusinessType(),orderStateVerifyDTO.getFamilyId(), orderApproveDTO.getRescueYears());


        int rst = familyMainHistoryWriteService.backHistory(orderApproveDTO.getOrderId(), orderStateVerifyDTO.getFamilyId(),
                orderApproveDTO.getRescueYears(), orderApproveDTO.getSalvationNo(), userAccountVo);
        if(rst <= 0){
            log.info("{}", orderStateVerifyDTO.getOrderId());
            throw  new BizException("-1","备份历史数据失败");
        }


        String remindBankInfo = "";
        if("1".equals(orderApproveDTO.getApprovalResult())) {

            this.changeLowerStatus(orderStateVerifyDTO.getOrderId(),orderStateVerifyDTO.getFamilyId(),orderStateVerifyDTO.getBusinessType());


            remindBankInfo = this.remindBankInfo(orderStateVerifyDTO.getFamilyId(),orderStateVerifyDTO.getBusinessType());

            this.approvalResultYes(orderApproveDTO, orderStateVerifyDTO, userAccountVo);
        }


        suspendManagementService.updateSuspendFamily(orderApproveDTO.getOrderId(),orderStateVerifyDTO.getNextState());

        scheduleCheckService.sendApproveResult(Arrays.asList(orderApproveDTO.getOrderId()),Constant.BusinessCode.DIBAO,userAccountVo);

        return remindBankInfo;
    }

    public String remindBankInfo(String familyID,String businessType){
        List<BankEntity> list = bankReadService.getBankByfamilyId(familyID,businessType);
        if(!list.isEmpty()){
            String master = list.get(0).getMasterAccount();
            String agent = list.get(0).getAgentAccount();
            if(StringUtils.isEmpty(master) && StringUtils.isEmpty(agent)){
                return "未录入银行卡信息";
            }

        }else{
            return "未录入银行卡信息";
        }
        return "";
    }

    public void changeLowerStatus(String orderId,String familyId,String businessType){
        if(Constant.BusinessCode.DIBAO.equals(businessType)){

            FamilyMainEntity familyMainEntity = familyMainReadService.getById(familyId);
        }

    }




    @Override
    public void approveHouseholdCancel(OrderApproveDTO orderApproveDTO, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = this.isCanApprove(orderApproveDTO.getOrderId(), userAccountVo, "2",orderApproveDTO.getApprovalResult());


        if("1".equals(orderApproveDTO.getApprovalResult())) {
            fundPayReadService.verifySuspendFundPayThrow(orderStateVerifyDTO.getSourOrderId(),orderStateVerifyDTO.getBusinessType(), orderStateVerifyDTO.getCountyCode(),
                    orderStateVerifyDTO.getStandType(), orderApproveDTO.getRescueYears(), orderStateVerifyDTO.getSupplyType());
        }

        log.info("执行整户停保的update语句");
        orderDetailWriteService.saveSalvationApprove(orderApproveDTO, userAccountVo);

//        familyMainWriteService.updateSalvationNo(orderApproveDTO.getOrderId(),orderApproveDTO.getSalvationNo());


        this.updateHouseholdCancelOrder(orderStateVerifyDTO, orderApproveDTO);

        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getNextState())){

            return;
        }

        int rst = familyMainHistoryWriteService.backHistory(orderApproveDTO.getOrderId(), orderStateVerifyDTO.getFamilyId(),
                orderApproveDTO.getRescueYears(), orderApproveDTO.getSalvationNo(), userAccountVo);
        if(rst <= 0){
            log.info("{}", orderStateVerifyDTO.getOrderId());
            throw  new BizException("-1","备份历史数据失败");
        }


        if("1".equals(orderApproveDTO.getApprovalResult())) {
            this.houseHoldCancelResultYes(orderApproveDTO, orderStateVerifyDTO, userAccountVo);
        }

        suspendManagementService.updateSuspendFamily(orderApproveDTO.getOrderId(),orderStateVerifyDTO.getNextState());

        scheduleCheckService.sendApproveResult(Arrays.asList(orderApproveDTO.getOrderId()),Constant.BusinessCode.DIBAO,userAccountVo);
    }


    @Override
    public  void saveApproveSalvation(OrderApproveDTO orderApproveDTO, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = this.isCanApprove(orderApproveDTO.getOrderId(), userAccountVo, "1",orderApproveDTO.getApprovalResult());

        OrderEntity orderEntity = orderReadService.getById(orderApproveDTO.getOrderId());

        int householdCancel = familyMemberReadService.isHouseholdCancel(orderApproveDTO.getOrderId());
        if(householdCancel<1){

            salvationApplyService.verifyMemberAssets(orderApproveDTO.getOrderId());
        }

        if("1".equals(orderApproveDTO.getApprovalResult())) {
            fundPayReadService.verifyFundPayThrow(orderStateVerifyDTO.getBusinessType(), orderStateVerifyDTO.getCountyCode(),
                    orderStateVerifyDTO.getStandType(), orderApproveDTO.getRescueYears(), orderStateVerifyDTO.getSupplyType(),
                    Constant.FundType.CAPITAL_FUND_PAY);
        }

        orderDetailWriteService.saveSalvationApprove(orderApproveDTO, userAccountVo);

        familyMainWriteService.updateSalvationNo(orderApproveDTO.getOrderId(),orderApproveDTO.getSalvationNo());

        familyMemberWriteService.updateFirstStartDate(orderStateVerifyDTO.getType(),orderApproveDTO.getOrderId(),orderStateVerifyDTO.getBusinessType(),orderEntity.getFamilyId(), orderApproveDTO.getRescueYears());

        this.auditUpdateOrderState(orderEntity,orderStateVerifyDTO,orderApproveDTO.getRescueYears());
    }


    public void approvalResultYes(OrderApproveDTO orderApproveDTO, OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo){

        int rst = familySalaryWriteService.updateStartDate(orderApproveDTO.getOrderId(), orderApproveDTO.getRescueYears());
        if(rst <= 0){
            throw new BizException("-1", "待遇开始时间修改失败");
        }

        if(Constant.OrderType.RECHECK.equals(orderStateVerifyDTO.getType())){
            salaryChangeWriteService.insertByRecheck(orderApproveDTO.getRescueYears(),
                    orderStateVerifyDTO.getOrderId(),
                    orderStateVerifyDTO.getSourOrderId(),
                    orderStateVerifyDTO.getFamilyId(),
                    orderStateVerifyDTO.getAreaCode(),
                    orderStateVerifyDTO.getCountyCode());
        }else{
            salaryChangeWriteService.insertByNew(orderApproveDTO.getRescueYears(),
                    orderStateVerifyDTO.getOrderId(),
                    orderStateVerifyDTO.getFamilyId(),
                    orderStateVerifyDTO.getAreaCode(),
                    orderStateVerifyDTO.getCountyCode());
        }




//        orderEntity.setOrderId(orderStateVerifyDTO.getOrderId());
//        orderEntity.setFamilyId(orderStateVerifyDTO.getFamilyId());
//        orderEntity.setMemberId(orderStateVerifyDTO.getMemberId());
//        orderEntity.setAreaCode(orderStateVerifyDTO.getAreaCode());
//        orderEntity.setCountyCode(orderStateVerifyDTO.getCountyCode());
//        orderEntity.setBusinessType(orderStateVerifyDTO.getBusinessType());
//        orderEntity.setIdcard(orderStateVerifyDTO.getIdcard());

    }

    public BaseResult<Map>  verifyHouseholdCancelFundPay(OrderApproveDTO orderApproveDTO, UserAccountVo accountVo){
        BaseResult<Map> rstMsg = new BaseResult<>();
        Map<String,Object> rstMap = new HashMap<>();

        OrderStateVerifyDTO orderStateVerifyDTO = this.isCanApprove(orderApproveDTO.getOrderId(), accountVo, "1",orderApproveDTO.getApprovalResult());

        String now = DateUtil.getMonthString();
        String maxMonth = fundPayReadService.verifyFundPay(orderStateVerifyDTO.getBusinessType(), orderStateVerifyDTO.getCountyCode(),
                orderStateVerifyDTO.getStandType(), now, orderStateVerifyDTO.getSupplyType(),
                Constant.FundType.CAPITAL_FUND_PAY,"1");
        if(StringUtils.isNotBlank(maxMonth)){
            Calendar calendar = Calendar.getInstance();
            try {
                Date date = DateUtil.sdf2.parse(maxMonth);
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd");
                maxMonth = sdf1.format(date);
                calendar.setTime(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            calendar.add(Calendar.MONTH,1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            rstMap.put("rescueYears",sdf.format(calendar.getTime()));
            rstMap.put("fundayMonth",maxMonth);
        }
        rstMsg.setData(rstMap);
        return rstMsg;
    }

    public void houseHoldCancelResultYes(OrderApproveDTO orderApproveDTO, OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo){

        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(DateUtil.sdf2.parse(orderApproveDTO.getRescueYears()+"-1"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String monthDay = DateUtil.sdf2.format(calendar.getTime());
        calendar.add(Calendar.MONTH,-1);

        String endDate = DateUtil.sdf2.format(calendar.getTime());

//        int rst = familySalaryWriteService.updateEndDate(orderApproveDTO.getOrderId(), endDate);


        OrderEntity entity = new OrderEntity();
        entity.setOrderId(orderStateVerifyDTO.getOrderId());
        entity.setSourOrderId(orderStateVerifyDTO.getSourOrderId());
        entity.setFamilyId(orderStateVerifyDTO.getFamilyId());
        entity.setAreaCode(orderStateVerifyDTO.getAreaCode());
        entity.setCountyCode(orderStateVerifyDTO.getCountyCode());
        salaryChangeWriteService.houseHoldCancelSalaryChange(entity,monthDay,"整户注销",Constant.SalaryChangeType.CHANGE_EXPIRE);
    }

    @Override
    public BaseResult<Boolean> confirmFamilySalaryInfo(OrderSalaryDTO orderSalary, Map<String, String> familyMemberMapParam, UserAccountVo userAccountVo) {

        int familySaveMemberObject = this.verifySaveMember(familyMemberMapParam);


        return familySalaryWriteService.confirmFamilySalaryDiBao(orderSalary, familyMemberMapParam,   familySaveMemberObject, userAccountVo);
    }


    private int verifySaveMember(Map<String, String> familyMemberMapParam){

        int familySaveMemberObject = 0;
        for(String orderId : familyMemberMapParam.keySet()){
            familySaveMemberObject += "1".equals(familyMemberMapParam.get(orderId)) ? 1 : 0;
        }
        if(familySaveMemberObject == 0){
            throw new BizException("-1", "该家庭无保障成员，无法计算待遇");
        }
        return familySaveMemberObject;
    }



    @Override
    public int chengeMemberSaveObject(String orderId,String familyId,String memberId,String type,String isMaster){
        return familyMemberWriteService.chengeMemberSaveObject(orderId,familyId,memberId,type,isMaster);
    }

    @Override
    public int changDocHelpPoor(String orderId,String docHelpPoor){
        return familyMemberWriteService.updateDocHelpPoor(orderId,docHelpPoor);
    }


    @Override
    public void isCanUploadCheckFile(String familyId,String orderId){


        salvationApplyService.verifyFamilyMasterNum(familyId);





        salvationApplyService.verifyCompleteMemberInfo(familyId);


        salvationApplyService.verifyExpireCheck(orderId);

    }
    @Override
    public int uploadCheckFile(MultipartFile[] files, String orderId,String reason,String areaCode){

        if(files==null||files.length<1){
            throw new BizException("-1","没有核对文件");
        }
        int res = 0;
        try{
            String [] keys = new String[files.length];
            int i = 0;
            for(MultipartFile file:files) {
                if(!file.getOriginalFilename().endsWith("pdf") && !file.getOriginalFilename().endsWith("PDF") && !file.getOriginalFilename().endsWith("fdf")){
                    throw new BizException("-1","请上传PDF格式核对报告");
                }
                String objectkey = fileService.upload(file.getInputStream(), file.getOriginalFilename());
                keys[i] = objectkey;
                i++;
            }
            OrderEntity orderEntity = orderReadService.getById(orderId);
            CheckEntity check  = new CheckEntity();
            String batchNo = BatchNoUtil.getBatch(Constant.BusiCode.CHECK_BATCH, areaCode);
            check.setCheckResultState(Constant.CheckResultState.SUCCESS);
            check.setOrderId(orderId);
            check.setAreaCode(areaCode);
            check.setFamilyId(orderEntity.getFamilyId());
            check.setIdcard(orderEntity.getIdcard());
            check.setStandType(orderEntity.getStandType());
            check.setBusinessType(orderEntity.getBusinessType());
            check.setCheckBatchNo(batchNo);
            check.setCheckRemark(reason);
            res = checkWriteService.uploadCheckFile(check,keys);
        }catch(IOException e){
            e.printStackTrace();
            log.error("核对文件上传失败");
            throw new BizException(FailureCode.ERR_20078);
        }
        return res;
    }

    @Override
    public ExcelInfo exportTownSalvation(OrderListSearchParam param, UserAccountVo accountVo){
        ExcelInfo excelInfo = null;
        QueryParamUtil.setBaseParamValue(param,accountVo);
        param.setBusinessType(Constant.BusinessCode.DIBAO);
        if("1".equals(param.getExportType())){



            List<OrderListPendingExcelDTO> list = orderReadService.exportTownSalvation(param);
            excelInfo = exportExcelService.exportOrgOpLogs(OrderListPendingExcelDTO.class,list,"低保乡镇待办信息.xls",
                    "最低生活保障乡镇待办列表","最低生活保障乡镇待办列表",false);
        }else if("2".equals(param.getExportType())){

            List<OrderListCPendingExcelDTO> list = orderReadService.exportCountySalvation(param);
            excelInfo = exportExcelService.exportOrgOpLogs(OrderListCPendingExcelDTO.class,list,"低保区县待办信息.xls",
                    "最低生活保障区县待办列表","最低生活保障区县待办列表",false);
        }


        return excelInfo;
    }


    @Override
    public void sendBackSys(String orderId, String content, UserAccountVo userAccountVo, String businessType){

        OrderStateEntity orderStateEntity = new OrderStateEntity();
        orderStateEntity.setOrderId(orderId);
        orderStateEntity.setState(Constant.BizStateNew.SYS_BACK);
        orderStateEntity.setBizState(Constant.BizStateNew.SYS_BACK);
        orderStateEntity.setBackContent(content);
        orderWriteService.updateState(orderStateEntity);


    }


    @Override
    public int decideIncome(String orderId,String familyId){
        return  checkReadService.decideIncome(orderId,familyId);

    }

    @Override
    public Map<String,Object> queryReportDetail(String orderId) {
        Map<String,Object> rstMap = new HashMap<>();

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);
        rstMap.put("reportDate",orderStateVerifyDTO.getUpdateTime());

        return rstMap;
    }


    @Override
    public Map<String, List<String>> sendBatchCheck(List<CheckDTO> checkList, UserAccountVo userAccountVo, String businessType,String checkType) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();


        checkList = verifyNoCompleteOrder(checkList,idcardCheckRstMsg);
        if(checkList.size() == 0 ){

            return idcardCheckRstMsg;
        }


        this.verifyNoCompleteCheck(checkList, idcardCheckRstMsg);
        if(checkList.size() == 0){

            return idcardCheckRstMsg;
        }


        checkList = this.verifyNoCompleteInfo(checkList, idcardCheckRstMsg);
        if(checkList.size() == 0){

            return idcardCheckRstMsg;
        }


        log.info("开始保存数据到check表");
        List<CheckEntity> entities = checkWriteService.addCheck(checkList, userAccountVo.getAreaCode(), Constant.CheckState.WIAT_SEND, checkType, businessType);

        List<String> batchNo = entities.stream().map(checkEntity -> checkEntity.getCheckBatchNo()).distinct().collect(Collectors.toList());

        recheckBatchWriteService.batchInsert(entities,userAccountVo);

        log.info("发送数据给核对中心");
        String checkMsg = scheduleCheckService.sendCheckInfo(checkList,Constant.BusinessCode.DIBAO,userAccountVo,checkType);
        if(StringUtils.isNotBlank(checkMsg)){
            idcardCheckRstMsg.put("checkMsg",Arrays.asList(checkMsg));
        }

        recheckBatchWriteService.updateStateByBatchNo(batchNo);

        return idcardCheckRstMsg;
    }


    public List<CheckDTO> verifyNoCompleteOrder(List<CheckDTO> checkList,Map<String, List<String>> idcardCheckRstMsg){
        List<String> familyIds = checkList.stream().map(checkDTO -> checkDTO.getFamilyId()).collect(Collectors.toList());

        List<String> familyIdInBusiness = orderReadService.selectFamilyIdInBusiness(familyIds);
        if(CollectionUtils.isNotEmpty(familyIdInBusiness)){

            List<String> idCards = checkList.stream().filter(c -> familyIdInBusiness.contains(c.getFamilyId())).map(checkDTO -> checkDTO.getIdcard()).collect(Collectors.toList());
            idcardCheckRstMsg.put("idcardInBusiness",idCards);
            checkList = checkList.stream().filter(c -> !familyIdInBusiness.contains(c.getFamilyId())).collect(Collectors.toList());
        }
        return checkList;
    }

    public List<CheckDTO> verifyNoCompleteInfo(List<CheckDTO> checkList,Map<String, List<String>> idcardCheckRstMsg){

        List<String> orderIds = checkList.stream().map(checkDTO -> checkDTO.getOrderId()).collect(Collectors.toList());

        List<String> familyUnnormalMaster = familyMemberHistoryReadService.getUnnormalMasterByFamilyIds(orderIds);
        if(CollectionUtils.isNotEmpty(familyUnnormalMaster)){

            List<String> unnormalIdcard = checkList.stream().filter(c -> familyUnnormalMaster.contains(c.getOrderId())).map(checkDTO -> checkDTO.getIdcard()).collect(Collectors.toList());
            idcardCheckRstMsg.put("masterError",unnormalIdcard);
            checkList = checkList.stream().filter(c -> !familyUnnormalMaster.contains(c.getOrderId())).collect(Collectors.toList());
            if(checkList.size() == 0){

                return checkList;
            }
        }


        orderIds =  checkList.stream().map(checkDTO -> checkDTO.getOrderId()).collect(Collectors.toList());
        List<String> noAuthorOrderId = orderCertReadService.selectOrderNoAuthorFile(orderIds);
        if(CollectionUtils.isNotEmpty(noAuthorOrderId)){

            List<String> noAuthorIdcard = checkList.stream().filter(c -> noAuthorOrderId.contains(c.getOrderId())).map(checkDTO -> checkDTO.getIdcard()).collect(Collectors.toList());
            idcardCheckRstMsg.put("noAuthorCert",noAuthorIdcard);
            checkList = checkList.stream().filter(c -> !noAuthorOrderId.contains(c.getOrderId())).collect(Collectors.toList());
            if(checkList.size() == 0){

                return checkList;
            }
        }

        orderIds =  checkList.stream().map(checkDTO -> checkDTO.getOrderId()).collect(Collectors.toList());
        List<String> orderIdNoIdcardCert = orderCertReadService.getHistoryOrderIdNoIdcardCert(orderIds);
        if(CollectionUtils.isNotEmpty(orderIdNoIdcardCert)){

            List<String> noExistCert = checkList.stream().filter(c -> orderIdNoIdcardCert.contains(c.getOrderId())).map(checkDTO -> checkDTO.getIdcard()).collect(Collectors.toList());
            idcardCheckRstMsg.put("memberNoExistCert",noExistCert);
            checkList = checkList.stream().filter(c -> !orderIdNoIdcardCert.contains(c.getOrderId())).collect(Collectors.toList());
            if(checkList.size() == 0){

                return checkList;
            }
        }

        if("1".equals(checkList.get(0).getFamilySupport())){

            orderIds =  checkList.stream().map(checkDTO -> checkDTO.getOrderId()).collect(Collectors.toList());
            List<String> noAuthorSupport = orderCertReadService.selectSupportAuthorList(orderIds);
            if(CollectionUtils.isNotEmpty(noAuthorSupport)){
                idcardCheckRstMsg.put("noAuthorSupport",noAuthorSupport);
                checkList = checkList.stream().filter(c -> !noAuthorSupport.contains(c.getIdcard())).collect(Collectors.toList());
            }
            if(checkList.size() == 0){

                return checkList;
            }

            List<String> noIdCardSupport = orderCertReadService.cntSupportCertBeforeCheck(checkList);
            if(CollectionUtils.isNotEmpty(noIdCardSupport)){
                idcardCheckRstMsg.put("noIdCardSupport",noIdCardSupport);
                checkList = checkList.stream().filter(c -> !noIdCardSupport.contains(c.getIdcard())).collect(Collectors.toList());
            }
        }
        return checkList;
    }
}
